package com.lyhengtongwl.zqsnews.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.SlidingTabLayout;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.ForwardAdapter;
import com.lyhengtongwl.zqsnews.base.BaseFragment;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.manage.MyMediaManager;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.NoVerifyTask;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.ui.activity.NewsEarnActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsLoginActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsSearchActivity;
import com.lyhengtongwl.zqsnews.ui.fragment.forward.ForwardFragments;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class NewsByForwardFragment extends BaseFragment {
    @BindView(R.id.stl)
    SlidingTabLayout stl;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.iv_earn)
    ImageView imageView;


    private boolean isFirst = true;
    public static JSONArray adArray;
    public static JSONArray moneyMsgArray;
    private boolean isHide = true;
    private List<View> views;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_byforward, null);
    }

    @OnClick({R.id.iv_mmWay, R.id.iv_earn, R.id.et_search})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_mmWay://赚钱小技巧
                new CenterDialog(R.layout.moneymake_tips, getActivity()).showEarnPrompt();
                break;
            case R.id.iv_earn://收益详情
                String userId = SPUtils.get(App.getContext(), "userId", "") + "";//获取userId
                if (!userId.equals("")) {
                    imageView.setImageResource(R.drawable.red_normal);
                    startActivity(new Intent(getActivity(), NewsEarnActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), NewsLoginActivity.class));
                }
                break;
            case R.id.et_search://
                startActivity(new Intent(getActivity(), NewsSearchActivity.class));
                break;

        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            // 检测是否有收益
            checkEarn();
            if (isFirst) {
                isFirst = false;
                initTab();
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String str) {
        //获取出价记录  然后进行设置
        try {
            //重新刷数据
            if ("checkEarn".equals(str)) {
                if (!isFirst) {

                    //检测是否收益
                    checkEarn();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //收益动画
    private void checkEarn() {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        if (!userId.equals("")) {
            Task.getApiService().isHaveEarn(userId).enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
                @Override
                protected void onSuccess(Response<NewsBaseEntity> response) {
                    if ("1".equals(response.body().getCode())) {
                        String jsonString = JSON.toJSONString(response.body().getData());
                        JSONObject jsonObject = JSONObject.parseObject(jsonString);
                        if (jsonObject.getInteger("lookStatus") == 0) {
                            DisplayMetrics dm = new DisplayMetrics();
                            //取得窗口属性
                            Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(dm);
                            //        //窗口的宽度
                            //        //窗口的宽度
                            int screenWidth = dm.widthPixels;
                            int screenHeigh = dm.heightPixels;
                            int top = ScreenUtil.dip2px(App.getContext(), 44) + ScreenUtil.getStatusBarHeight(getContext());
                            int x = screenWidth - ScreenUtil.dip2px(App.getContext(), 40);
                            int y = top;
                            animation(x, y);
                        }
                    }
                }

                @Override
                protected void onFailure(Throwable t) {

                }
            });
        }
    }

    //左右摇晃
    private void animation(int x, int y) {
        Log.e("位置坐标：", "animation: " + x + "***" + y);
        MyMediaManager.getInstance().playAudio(R.raw.earn, imageView);  //这是左右摇晃动画

//        new CenterDialog(R.layout.earn_promit, getActivity()).showEarn(x, y);
    }


    //初始化顶部导航栏
    private void initTab() {
        List<String> mTitles = new ArrayList<>();
        List<String> mNewsType = new ArrayList<>();

        NoVerifyTask.getApiService().getArticleType().enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    assert response.body() != null;
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);

                    adArray = jsonObject.getJSONArray("adsList");
                    JSONArray articleTypeArray = jsonObject.getJSONArray("articleTypeList");
                    moneyMsgArray = jsonObject.getJSONArray("moneyMsgList");
                    for (int i = 0; i < articleTypeArray.size(); i++) {
                        mTitles.add(articleTypeArray.getJSONObject(i).getString("typeName"));
                        mNewsType.add(articleTypeArray.getJSONObject(i).getInteger("exCodingId") + "");
                    }
                    List<Fragment> mFragments = new ArrayList<>();
                    mFragments.clear();
                    for (int i = 0; i < mTitles.size(); i++) {
                        mFragments.add(new ForwardFragments(mNewsType.get(i)));
                    }

                    //new一个适配器
                    ForwardAdapter forwardAdapter = new ForwardAdapter(getChildFragmentManager(), mFragments, mTitles);
                    //设置ViewPager与适配器关联
                    vp.setAdapter(forwardAdapter);
                    vp.setOffscreenPageLimit(mTitles.size() - 1);
                    //设置Tab与ViewPager关联
                    stl.setViewPager(vp);
                    stl.setCurrentTab(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });

    }
}
